<template>
  <el-dialog v-model="itemsVisible" title="配置审批" width="55%" top="2vh">
    <el-form class="my-form" :model="obj" label-position="right" label-width="8rem">
      <el-form-item label="审批模版" prop="budgetName">
        <el-select v-model="obj.approveId" style="width: 480px;" placeholder="请选择" clearable filterable @change="changeApprove" disabled>
          <el-option v-for="item in approveList" :key="item.id" :label="`${item.approveCode} - ${item.approveName}`" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="addApproveNode">新增审批节点</el-button>
      </el-form-item>
      <el-form class="my-form" ref="objForm" :rules="objRules" :model="approveNodeList" label-position="right" label-width="8rem">
        <el-form-item label="审批流" v-if="approveNodeList.length > 0">
        <el-timeline class="timeline">
          <el-timeline-item placement="top"
                            v-for="(node, index) in approveNodeList"
                            :key="index"
                            :timestamp="`审批节点${node.approveNodeNo}(${node.approveNodeSource === '1' ? '模版' : '自定义'})`"
                            center>
            <div class="timeline-item">
              <el-form-item label="审批节点名称" prop="approveNodeName">
                <el-input v-model="node.approveNodeName" placeholder="请输入节点名称" :disabled="node.approveNodeSource === '1'" />
              </el-form-item>
              <el-form-item label="是否会签节点" prop="isCountersign" style="margin: 10px 0;" v-if="node.approveNodeSource === '1'">
                <el-radio-group v-model="node.isCountersign" :disabled="node.approveNodeSource === '1'">
                  <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="审批节点类型" prop="approveNodeType" style="margin: 10px 0;" v-if="node.approveNodeSource === '1'">
                <el-radio-group v-model="node.approveNodeType" :disabled="node.approveNodeSource === '1'">
                  <el-radio-button v-for="(item,index) in getEnumList('ApproveNodeType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="审批节点组织架构" prop="approveNodeOrgId" style="margin: 10px 0;" v-if="node.approveNodeType === '1'">
                <Organization v-model="node.approveNodeOrgId" keyName="id" keyShow="organizationName" placeholder="部门" title="部门查询" :disabled="node.approveNodeSource === '1'" />
              </el-form-item>
              <el-form-item label="审批节点用户" prop="approveNodeUserId" style="margin: 10px 0;" v-if="node.approveNodeType === '2'">
                <User v-model="node.approveNodeUserId" keyName="id" keyShow="name" placeholder="用户" title="用户查询" :disabled="node.approveNodeSource === '1'" />
              </el-form-item>
              <el-form-item label="审批节点角色" prop="approveNodeRoleId" style="margin: 10px 0;" v-if="node.approveNodeType === '3'">
                <Role v-model="node.approveNodeRoleId" keyName="id" keyShow="roleName" placeholder="角色" title="角色查询" :disabled="node.approveNodeSource === '1'" />
              </el-form-item>
              <el-form-item v-if="node.approveNodeSource === '2'">
                <el-button type="danger" @click="delApproveNode(node.approveNodeNo)" :disabled="node.approveNodeSource === '1'">删除该节点</el-button>
              </el-form-item>
            </div>
          </el-timeline-item>
        </el-timeline>
      </el-form-item>
      </el-form>
    </el-form>
    <div style="text-align:right;">
      <el-button type="danger" @click="itemsVisible=false">关闭</el-button>
      <el-button type="primary" @click="doSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {ref, watch} from "vue";
import {doGet} from "@/config/http";
import {
  alertErrorMsg,
  customValidator,
  getEnumList,
  getListPageSize,
  isNullOrUndefinedOrEmpty,
  svc
} from "@/config/common";
import Organization from "@/views/components/base/selectOrganization.vue";
import User from "@/views/components/base/selectUser.vue";
import Role from "@/views/components/base/selectRole.vue";
import initListStore from '@/store/modules/initList'

const objForm = ref(null)
const obj = ref({
  approveId: null,
})

const itemsVisible = ref(false)
const business = ref(null)
const businessId = ref(null)

const props = defineProps({
  itemsVisible: {
    type: Boolean,
    default: false,
  },
  business: {
    type: String,
    default: null,
  },
  businessId: {
    type: String,
    default: null,
  },
})

const objRules = {
  approveId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '审批模版ID', trigger: ['blur', 'change'] }],
  approveNodeNo: [{ required: false, validator: customValidator, min: 0, max: 3, label: '审批节点编号', trigger: ['blur', 'change'] }],
  approveNodeName: [{ required: true, validator: customValidator, min: 0, max: 100, label: '审批节点名称', trigger: ['blur', 'change'] }],
  approveNodeType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '审批节点类型', trigger: ['blur', 'change'] }],
  approveNodeOrgId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '审批节点组织架构ID', trigger: ['blur', 'change'] }],
  approveNodeRoleId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '审批节点角色ID', trigger: ['blur', 'change'] }],
  approveNodeUserId: [{ required: false, validator: customValidator, min: 0, max: 250, label: '审批节点用户ID', trigger: ['blur', 'change'] }],
  isCountersign: [{ required: false, validator: customValidator, min: 0, max: 20, label: '是否会签节点', trigger: ['blur', 'change'] }],
}

const emit = defineEmits();

// const governmentList = ref([])
const organizationList = initListStore().organizationList
const userList = initListStore().userList
const roleList = initListStore().roleList

const approveList = ref([])
const approveNodeList = ref([])
const emptyApproveNode = {
  approveNodeSource: '2',
  approveNodeName: '审批节点1',
  approveNodeType: '2',
  approveNodeOrgId: null,
  approveNodeRoleId: null,
  approveNodeUserId: null,
  approveNodeNo: 1,
  isCountersign: '0', // 是否会签节点
}

// const initList = async () => {
//   if (!itemsVisible.value) {
//     return
//   }
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/role/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   roleList.value = resArray[3]['records']
// }

watch(() => [props.itemsVisible, props.business, props.businessId], async vals => {
  itemsVisible.value = vals[0]
  business.value = vals[1]
  businessId.value = vals[2]
  if (isNullOrUndefinedOrEmpty(business) || isNullOrUndefinedOrEmpty(businessId)) {
    return
  }
  if (itemsVisible.value) {
    // await initList()
    doGet(svc, '/customApprove/queryApproveByBusiness', {business: business.value, businessId: businessId.value}, false).then(res => {
      approveList.value = res
      if (approveList.value.length > 0) {
        obj.value.approveId = approveList.value[0].id
        changeApprove()
      }
    })
  }
})

async function changeApprove() {
  approveNodeList.value = await doGet(svc, '/approve-node/listByField', {field:'approveId', values:obj.value.approveId}, false)
  approveNodeList.value?.map(item => item.approveNodeSource = '1')

  approveNodeList.value.map(item => {
    const organizationIds = item?.approveNodeOrgId?.split(',')
    item.approveNodeOrgNames = organizationList.value?.filter(item => organizationIds?.includes(item.id)).map(m => m.name).join(',')
    const roleIds = item?.approveNodeRoleId?.split(',')
    item.approveNodeRoleNames = roleList.value?.filter(item => roleIds?.includes(item.id)).map(m => m.name).join(',')
    const userIds = item?.approveNodeUserId?.split(',')
    item.approveNodeUserNames = userList.value?.filter(item => userIds?.includes(item.id)).map(m => m.name).join(',')
  })
}

function addApproveNode() {
  if (approveNodeList.value.length >= 5) {
    return
  }
  let o = Object.assign({}, emptyApproveNode)
  let nodeIdx = approveNodeList.value.length + 1
  o.approveNodeNo = nodeIdx
  o.approveNodeName = '新增审批节点' + nodeIdx
  approveNodeList.value.unshift(o)
  let no = 1;
  approveNodeList.value.map(item => item.approveNodeNo = no++)
}

function delApproveNode(nodeIdx) {
  let idx = approveNodeList.value.findIndex(item => item['approveNodeNo'] === nodeIdx)
  approveNodeList.value.splice(idx, 1)
  let no = 1;
  approveNodeList.value.map(item => item.approveNodeNo = no++)
}

async function doSubmit() {
  // console.log('objForm', objForm.value)
  // let v = await objForm.value.validate().catch((err)=>{return err})
  // if (v !== true) {
  //   alertErrorMsg('表单验证不通过，请检查数据。')
  //   return
  // }
  // return
  obj.value.approveNodes = approveNodeList.value
  console.debug('obj', obj.value)
  emit('doSubmit', obj.value)
}
</script>
<style scoped>
.timeline {
  width: 100%;
  margin-right: 50px;
}
.timeline-item {
  margin: 10px 0;
  border:1px solid #ccc;
  border-radius: 5px;
  padding: 10px 25px;
}
</style>
